import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

interface userState {
  loading: boolean;
  error: string | null;
  token: string | null;
}

const initialState: userState = {
  loading: false,
  error: null,
  token: sessionStorage.getItem("token")||"",
};
// export const getuser = createAsyncThunk(
//   "getuser/user",
//   async (touristRouteId: string, thunkAPI) => {
//     // setLoading(true);
//     thunkAPI.dispatch(userSlice.actions.fetchStart());
//     try {
//       const { data } = await axios.get(
//         `http://123.56.149.216:8080/api/touristRoutes/${touristRouteId}`
//       );
//       // setProduct(data);
//       thunkAPI.dispatch(userSlice.actions.fetchSuccess(data));
//       // setLoading(false);
//     } catch (error: any) {
//       thunkAPI.dispatch(userSlice.actions.fetchFail(error.message));
//       // setError(error.message);
//       // setLoading(false);
//     }
//   }
// );
//promise
export const signIn = createAsyncThunk(
  "user/getuser",
  async (params: { email: string; password: string }, thunkAPI) => {
    const { data } = await axios.post(`http://123.56.149.216:8080/auth/login`, {
      email: params.email,
      password: params.password,
    });
    console.log(data);

    return data.token;
  }
);

//
//       thunkAPI.dispatch(userSlice.actions.fetchSuccess(data));
//       // setLoading(false);
//     } catch (error: any) {
//       thunkAPI.dispatch(userSlice.actions.fetchFail(error.message));
//       // setError(error.message);
//       // setLoading(false);
//     }
//   }
// );

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    logOut: (state) => {
      state.token = null;
      sessionStorage.removeItem("token");
    },
  },
  extraReducers: {
    [signIn.pending.type]: (state) => {
      // return {...state,loading:true}
      state.loading = true;
    },
    [signIn.fulfilled.type]: (state, action) => {
      state.token = action.payload;

      
      axios.defaults.headers.common.Authorization = `Bearer ${state.token}`
      state.loading = false;
      sessionStorage.setItem("token", action.payload);
    },
    [signIn.rejected.type]: (state, action: PayloadAction<string | null>) => {
      state.error = action.payload;
      state.loading = false;
    },
  },
});
